package com.group3.controller.Validated;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.*;
import java.util.regex.Pattern;

/**
 * Phone
 *
 * @author HY
 * 2021/06/14 15:02
 **/

@Constraint(validatedBy = PhoneSelect.PhoneValidator.class)
@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface PhoneSelect {

    /**
     * 错误提示
     */
    String message() default "手机号格式不合法";

    /**
     * 用于分组校验
     */
    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

//    具体规则
    class PhoneValidator implements ConstraintValidator<PhoneSelect, String> {

        private Pattern pattern = Pattern.compile("1(([38]\\d)|(5[^4&&\\d])|(4[579])|(7[0135678]))\\d{8}");

        @Override
        public void initialize(PhoneSelect phone) {
        }

        @Override
        public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
            //判断是否为null
            if (value == null){
                return true;
            }
            //判断是否为空字符串
            if (value == ""){
                return true;
            }
            return pattern.matcher(value).matches();
        }
    }

}
